package group6renderer;



import javax.swing.*;
import java.io.*;

/**
 * This class handles the logging of error strings and the bulding of a full error log file
 * 
 * Collaborators: Parser, GUI, Group6Renderer
 * @author Yiannis
 */
public class ErrorLog
{
	private static ErrorLog errorObj;
	private static boolean instance=false;
	
	/**
	 * Implementation of the singleton pattern
	 * @return the single instance of the ErrorLog class
	 */
	public static ErrorLog errorInstance()
	{
		if (!instance)
			{
				errorObj=new ErrorLog();
				instance=true;
			}
		
		return errorObj;
	}
	
	
	private String errors="\r\n ------------------"+Group6Renderer.htmlFile.getName().substring(0, Group6Renderer.htmlFile.getName().indexOf(".") - 1)+" HTML FILE  ERRORS----------------\r\n\r\n";
	private int errorCounter=0;

	private ErrorLog()
	{
		
	}

	
	
	/**
	 * Adds an error to the log
	 * @param The error string
	 */
	public void addError(String error)
	{
		errors+=error;
		errorCounter++;
		
	}
	
	/**
	 * Return the multiline string containing the error log
	 * @return the error log string
	 */
	public String getErrorsString()
	{
		return errors;	
	}

	/**
	 * Gets a new swing window containing the error log
	 * @return a JFrame object representing the error log window
	 */
	public JFrame getErrorsWindow()
	{
		JFrame errorFrame =new JFrame("Errors");
		errorFrame.setSize(600, 600);
		JTextArea stringText=new JTextArea(errors);
		
		JScrollPane sp = new JScrollPane(stringText);
		errorFrame.getContentPane().add(sp);
		//errorFrame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
		//errorFrame.getContentPane().add(stringText);
		stringText.setEditable(false);
		//errorFrame.setVisible(true);
		return errorFrame;
		
	}
	
	/**
	 * Writes the error log string to a text file with the same path as the html document with a .txt extension333
	 */
	public void sendErrorsToFile()
	{

		errors=errors+"\r\n\r\n\r\n--------------------------------------------\r\n\r\n TOTAL ERRORS : "+errorCounter;

		try 
		{
		FileWriter fileWriter = new FileWriter(Group6Renderer.htmlFile+"  Error Log.txt");


		BufferedWriter buffWriter = new BufferedWriter(fileWriter);

		buffWriter.write(errors);



		buffWriter.close();
		}


		catch(IOException e)
		{
		System.out.println("Exception "+ e);
		} 
	}
}
